package com.whh.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.whh.pojo.Role;
import com.whh.pojo.User;
import com.whh.service.role.RoleService;
import com.whh.service.role.RoleServiceImpl;
import com.whh.service.user.UserService;
import com.whh.service.user.UserServiceImpl;
import com.whh.util.Constants;
import com.whh.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/jsp/user.do")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        System.out.println("method----> " + method);

        if (method != null && method.equals("add")) {
            //增加操作
            this.add(request, response);
        } else if (method != null && method.equals("query")) {
            this.query(request, response);
        } else if (method != null && method.equals("getrolelist")) {
            this.getRoleList(request, response);
        } else if (method != null && method.equals("ucexist")) {
            this.UserCodeExist(request, response);
        } else if (method != null && method.equals("deluser")) {
            this.delUser(request, response);
        } else if (method != null && method.equals("view")) {
            this.getUserById(request, response, "userview.jsp");
        } else if (method != null && method.equals("modify")) {
            this.getUserById(request, response, "usermodify.jsp");
        } else if (method != null && method.equals("modifyexe")) {
            this.modify(request, response);
        } else if (method != null && method.equals("pwdmodify")) {
             this.pwdModify(request, response);
        } else if (method != null && method.equals("savepwd")) {
            this.updatePwd(request, response);
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    //查询所有用户信息
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端拿数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole=0;
        //获取用户列表
        UserService userServlet=new UserServiceImpl();
        List<User> userList=null;
        //第一次走这个请求 一定是第一页 页面大小固定
        int pageSize=5;
        int currentPageNo=1;
        if (queryUserName==null){
            queryUserName="";
        }

        if (temp!=null&& !temp.equals("")){
            queryUserRole =Integer.parseInt(temp);//给查询赋值
        }

        if (pageIndex!=null){
            currentPageNo=Integer.parseInt(pageIndex);
        }

        //获取用户的总数(分页：上一页，下一页)
        int totalCount=userServlet.getUserCount(queryUserName,queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount=((int)(totalCount/pageSize))+1;

        //控制首页和尾页
        //如果页面要小于1了 就显示第一页的东西

        if (currentPageNo<1){
            currentPageNo=1;
        }else if (currentPageNo>totalPageCount){//当前页面大于了最后一页
            currentPageNo=totalPageCount;
        }


        //获取用户列表展示
        userList=userServlet.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService=new RoleServiceImpl();
        List<Role> roleList=roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        req.setAttribute("totalPageCount",totalPageCount);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //修改用户密码
    public void  updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag=false;
        System.out.println(o!=null);
        System.out.println(StringUtils.isNullOrEmpty(newpassword));
        if (o!=null&&!StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag=userService.updatePwd(((User) o).getId(),newpassword);
            if (flag){
                req.setAttribute("message","修改密码成功，请退出，使用新的密码登录");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败");
            }
        }else {
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     //判断旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能Map 存入结果集
        Map<String,String> resultMap=new HashMap<String,String>();
        if (o==null){
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){
            //输入密码是否为空
            resultMap.put("result","error");
        }else{
            String userPassword=((User) o).getUserPassword();
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer=resp.getWriter();
            /*JsonArray 阿里巴巴的JSON工具类 转换格式*/
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("=========add");
        //获得前端数据
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        //把前端用户输入的数据传入实体类中与数据库进行映射
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUserRole(Integer.parseInt(userRole));
        user.setAddress(address);
        user.setPhone(phone);
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) (req.getSession().getAttribute(Constants.USER_SESSION))).getId());

        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }
    //根据userCode查询出User 用来判断用户名是否存在
    public void UserCodeExist(HttpServletRequest req, HttpServletResponse resp){
        String userCode=req.getParameter("userCode");
        HashMap<String, String> resultMap = new HashMap<>();

        if (StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode","exist");
        }else {
            UserService userService=new UserServiceImpl();
            User user=userService.selectUserCodeExist(userCode);
            if (user!=null){
                resultMap.put("userCode","exist");
            }else {
                resultMap.put("userCode","notexist");
            }
        }
        resp.setContentType("application/json");
        try {
            PrintWriter writer=resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //用户修改
    public void modify(HttpServletRequest req, HttpServletResponse resp){
        //获得前端数据
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        System.out.println("servlet---------->gogogo");
       //把前端的数据传入实体类中进行数据库的映射
        User user=new User();
        user.setId(Integer.parseInt(uid));
        user.setUserName(userName);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

       UserService userService=new UserServiceImpl();
       if (userService.modify(user)){
           try {
               resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
           } catch (IOException e) {
               e.printStackTrace();
           }
       }else {
           try {
               req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
           } catch (ServletException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }
    //查询指定用户信息
    public void getUserById(HttpServletRequest req, HttpServletResponse resp,String url){
        String uid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(uid)){
            try {
                //调用service层得到user对象
                UserService userService=new UserServiceImpl();
                User user = userService.getUserById(uid);
                req.setAttribute("user",user);
                req.getRequestDispatcher(url).forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //删除用户
    public void delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     String id=req.getParameter("uid");
     Integer delId=0;
     try {
         delId=Integer.parseInt(id);
     }catch (Exception e){
       delId=0;
     }
     HashMap<String,String> map=new HashMap<>();
     if (delId<=0){
         map.put("delResult","notexist");
     }else {
       UserService userService=new UserServiceImpl();
       if (userService.deleteUserById(delId)){
           map.put("delResult","true");
       }else {
           map.put("delResult","false");
       }
     }
    resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(map));
        writer.flush();
        writer.close();
    }
    //获得角色信息
    public void getRoleList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
}








